package com.cuitrip.business.home.recommend.ui;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cuitrip.apiservice.TrackBusiness;
import com.cuitrip.business.home.recommend.RecommendCardListFragment;
import com.cuitrip.business.home.recommend.model.HomeCard;
import com.cuitrip.business.home.travel.model.SelectInfo;
import com.cuitrip.business.track.TrackProxy;
import com.cuitrip.business.video.VideoActivity;
import com.cuitrip.service.R;
import com.lab.adapter.BaseHolderView;
import com.lab.adapter.IAdapterData;
import com.lab.logtrack.AppLog;
import com.lab.network.util.NetworkUtil;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.schemeurl.SchemeUrlHandler;
import com.lab.schemeurl.constant.Host;
import com.lab.schemeurl.url.UrlBuilder;
import com.lab.utils.ImageHelper;
import com.lab.utils.ToastUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 首页卡片的holder view
 * Created by ak
 */
public class CardItemHolderView extends BaseHolderView {

    @Bind(R.id.card_title)
    TextView titleView;
    @Bind(R.id.card_sub_title)
    TextView subTitleView;
    @Bind(R.id.card_img)
    ImageView cardImageView;
    @Bind(R.id.play_action)
    ImageView mPlayAction;
    private List<HomeCard> cardList = new ArrayList<>();
    private int page = 0;

    public CardItemHolderView(Context context) {
        super(context, R.layout.item_card);
    }

    @Override
    public void initView(View rootView) {
        this.setClickable(true);
        ButterKnife.bind(this);
    }

    public void setCurrentList(List<HomeCard> cards) {
        this.cardList = cards;
    }

    public void setPage(int page) {
        this.page = page;
    }

    private void showPlayAction() {
        mPlayAction.setVisibility(VISIBLE);
        titleView.setVisibility(GONE);
        subTitleView.setVisibility(GONE);
    }

    private void hidePlayAction() {
        mPlayAction.setVisibility(GONE);
        titleView.setVisibility(VISIBLE);
        subTitleView.setVisibility(VISIBLE);
    }

    @Override
    public void bindData(final IAdapterData data, final int position) {
        if (data instanceof HomeCard) {
            final HomeCard card = (HomeCard) data;
            ImageHelper.displayCtImage(((HomeCard) data).getBackPic(), cardImageView, ImageHelper.getCardFiveFourImageOptions());
            titleView.setVisibility(TextUtils.isEmpty(card.getTitle()) ? GONE : VISIBLE);
            titleView.setText(card.getTitle());
            subTitleView.setVisibility(TextUtils.isEmpty(card.getSubTitle()) ? GONE : VISIBLE);
            subTitleView.setText(card.getSubTitle());
            //解析url，如果有video则显示播放按钮
            try {
                if (!TextUtils.isEmpty(card.getUrl())) {
                    String url = URLDecoder.decode(card.getUrl(), "UTF-8");
                    Uri uri = Uri.parse(url);
                    String videoUrl = uri.getQueryParameter("video");
                    String isShared = uri.getQueryParameter("isShared");
                    if (!TextUtils.isEmpty(videoUrl)) {
                        showPlayAction();
                    } else {
                        hidePlayAction();
                    }
                } else {
                    hidePlayAction();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (NetworkUtil.getConnectState(AppCoreRuntime.context) == NetworkUtil.CONNECT_NONE) {
                        ToastUtil.toast(R.string.feedback_no_internet_1);
                        return;
                    }
                    if (!TextUtils.isEmpty(card.getUrl())) {
                        String url = card.getUrl();
                        try {
                            url = URLDecoder.decode(url, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            AppLog.e(e.getMessage());
                        }
                        UrlBuilder urlBuilder = new UrlBuilder(url);
                        if (SchemeUrlHandler.getInstance().isAppScheme(url)) {
                            if (Host.TRIP.getHostName().equals(Uri.parse(url).getHost().trim())
                                    || Host.RECOMMEND.getHostName().equals(Uri.parse(url).getHost().trim())
                                    || Host.SEARCH.getHostName().equals(Uri.parse(url).getHost().trim())) {
                                urlBuilder.addObject(SelectInfo.KEY_FROM, SelectInfo.FROM_HOME_CARD);
                                urlBuilder.addObject(SelectInfo.TITLE_KEY, card.getTitle());
                            }
                            urlBuilder.addObject("topicType", String.valueOf(card.getTopicType()));
                            urlBuilder.addObject("type", String.valueOf(card.getType()));
                        }else{
                            urlBuilder.addObject("url",String.valueOf(url));
                            urlBuilder.addObject("isShared",String.valueOf(card.getIsShared()));
                            urlBuilder.addObject("shareUrl",String.valueOf(card.getShareUrl()));
                            urlBuilder.addObject("title",String.valueOf(card.getTitle()));
                            urlBuilder.addObject("subTitle",String.valueOf(card.getSubTitle()));
                            urlBuilder.addObject("backPic",String.valueOf(card.getBackPic()));
                            urlBuilder.addObject("id",String.valueOf(card.getId()));
                        }
                        if (Host.SEARCH.getHostName().equals(Uri.parse(url).getHost().trim())) {
                            if (card.searchParam != null && !urlBuilder.contains("searchParam")) {
                                urlBuilder.addObject("searchParam", card.searchParam);
                            }
                        }
                        url = urlBuilder.toUrl();
                        String videoUrl = Uri.parse(url).getQueryParameter("video");
                        if (!TextUtils.isEmpty(videoUrl)) {
                            url = tryExcludeVideoUrl(url, videoUrl);
                            VideoActivity.startPlay(mContext, card.getSubTitle(), videoUrl, url);
                            return;
                        }
                        SchemeUrlHandler.getInstance().dispatch(mContext, Uri.parse(url));
                        List<String> ids = new ArrayList<String>();
                        for (HomeCard trip : cardList) {
                            ids.add(String.valueOf(trip.getId()));
                        }
                        TrackProxy.getInstance().operationAction(TrackBusiness.Source.RECOMMEND, TrackBusiness.Action.CLICK, String.valueOf(page), TrackProxy.getInstance().getCurrentPageIndex(RecommendCardListFragment.PAGE_SIZE, position), ids);
                    }

                }
            });
        }
    }

    private String tryExcludeVideoUrl(String url, String videoUrl) {
        String videoUrlWithAndParam = "&video=" + videoUrl;
        String videoUrlWithParam = "video=" + videoUrl;
        if (url.contains(videoUrlWithAndParam)) {
            url = url.replace(videoUrlWithAndParam, "");
        } else if (url.contains(videoUrlWithParam)) {
            url = url.replace(videoUrlWithParam, "");
        }
        return url;
    }


}
